package com.job.framework.config.sharding;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

/**
 * 表范围分片算法
 *
 * @author sunq
 */
public class RangeTableShardingAlgorithm implements RangeShardingAlgorithm<Date> {

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Date> rangeShardingValue) {

        final ArrayList<String> result = new ArrayList<>();
        final Range<Date> range = rangeShardingValue.getValueRange();

        Date startTime = range.lowerEndpoint();
        Date endTime = range.upperEndpoint();

        String startYearMonth = DateUtil.format(startTime, DatePattern.SIMPLE_MONTH_PATTERN);
        String endYearMonth = DateUtil.format(endTime, DatePattern.SIMPLE_MONTH_PATTERN);
        if (startYearMonth == endYearMonth) {
            return theSameMonth(startYearMonth, availableTargetNames, result);
        }
        return differentMonth(startYearMonth, endYearMonth, availableTargetNames, result);
    }


    // 同月
    private Collection<String> theSameMonth(String startMonthStr, Collection<String> availableTargetNames, ArrayList<String> result) {
        for (String availableTargetName : availableTargetNames) {
            if (availableTargetName.endsWith(startMonthStr)) result.add(availableTargetName);
        }
        return result;
    }

    // 不同月
    private Collection<String> differentMonth(String startYearMonthStr, String endYearMonthStr, Collection<String> availableTargetNames, ArrayList<String> result) {
        int startMonth = Integer.parseInt(startYearMonthStr);
        int endMonth = Integer.parseInt(endYearMonthStr);

        for (String availableTargetName : availableTargetNames) {
            for (int i = startMonth; i <= endMonth; i++) {
                if (availableTargetName.endsWith(String.valueOf(i))) result.add(availableTargetName);
            }
        }
        return result;
    }

}